package com.har.modules.web.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.har.common.constant.CodeConstant;
import com.har.common.utils.DateUtils;
import com.har.modules.web.dao.OrderDao;
import com.har.modules.web.entity.OrderEntity;
import com.har.modules.web.entity.extend.PolicyModel;
import com.har.modules.web.service.LoanHtService;
import com.har.modules.web.service.OrderService;
import com.har.service.HtService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;


@Slf4j
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {


    @Autowired
    private HtService htService;

    @Autowired
    private LoanHtService loanHtService;




    @Override
    public JSONObject createOrder(JSONObject dataJson) {

        //计算价格
        //插入订单
       OrderEntity orderEntity =  insertOrder(0.01);
        //插入保单

        //支付

        JSONObject reqJson = new JSONObject();
        reqJson.put("tradeName","");
        reqJson.put("tradeType","01");
        reqJson.put("orderNo",orderEntity.getOrderNo());
        reqJson.put("money",orderEntity.getMoney().setScale(2,BigDecimal.ROUND_HALF_UP));
        reqJson.put("tradeTime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));

        String result =  htService.orderPay(reqJson);


        log.info(result);


        return null;
    }



    private  OrderEntity insertOrder(Double money){

        OrderEntity entity = new OrderEntity();
        entity.setCreateTime(new Date());
        entity.setChannel(CodeConstant.ORDER_CHANNEL.HT.getCode());
        entity.setMoney(new BigDecimal(money));
        entity.setOrderNo(htService.generateOrderNo());
        entity.setPayRefund(CodeConstant.ORDER_PAY_REFUND.PAY.getCode());
        entity.setTradeType(CodeConstant.ORDER_TRADE_TYPE.PC.getCode());
        entity.setPayStatus(CodeConstant.ORDER_PAY_STATUS.PAY_COMMit.getCode());
        insert(entity);

        return  entity;

    }


    @Override
    public JSONObject insureInterface(JSONObject dataJson) {


        PolicyModel policyModel = loanHtService.policy(dataJson.getString("orderNo"));

        JSONObject insureJson  = JSONObject.parseObject(JSON.toJSONString(policyModel));

        String result = htService.policyHt(insureJson);

        log.info("ht insure result >> {}",result);


        return null;
    }
}
